package mx.tools;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.lang.reflect.*;

import org.codehaus.groovy.runtime.InvokerHelper;

/*
 * 工具类
 */
public class USys {   	
	/*
	 * 提供一个创建HashMap对象的简便方法，传入的多个参数视为 [名字 值] 对
	 */
	public static Map newMap(Object... objects ) throws Exception {
		Map result = new LinkedHashMap();
		if (null == objects)
			return result;
		
		List objlist = java.util.Arrays.asList(objects);
		Object field = null;
		for (int i=0; i<objlist.size(); i++) {
			if (null == field) {
				field = objlist.get(i);
			} else {
				result.put(field, objlist.get(i));
				field = null;
			}  
		}
		if (null != field)
			result.put(field, null);
		return result;
	}	
	
	public static List newList(Object... objects ) throws Exception {
		return java.util.Arrays.asList(objects);
	}
	
	public static void assertIt(boolean expr, String fmt, Object...objects) throws Exception {
		if (! expr) 
			throw new Exception(String.format(fmt, objects));
	}
	
	public static void raise(String fmt, Object...objects) throws Exception {
		throw new Exception(String.format(fmt, objects));
	}
	
		
	public static Object invokeMethod(Object object, String methodName, Object... args) throws Exception {
		try {
			return InvokerHelper.invokeMethod(object, methodName, args);
		} catch (Throwable t) {
			throw new Exception(t.getMessage());
		}
	}

	public static Object invokeStaticMethod(String className, String methodName, Object... args) throws Exception {
		return InvokerHelper.invokeStaticMethod(className, methodName, args);
	}
	
	/**
	 * 以路径方式访问树结构map中的某一节点数据
	 * @param map
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static <T> T mapGet(Map<String,Object> map, String path) throws Exception {
		String[] list = path.split("\\.");
		Object result = null;
		Map m = map;
		for (int i=0; i<list.length; i++) {
			String p =list[i];
			Object o = m.get(p);
			if (i != list.length-1) {
				m = (Map) o;
			} else {
				result = o;
			}
		}
		
		return (T) result;
	}
		
}
